# -*- coding: utf-8 -*-
# time: 2025/5/12 13:44
# file: TavilySeach_agent.py
# author: hanson
"""
https://app.tavily.com/home
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

"""
import os

from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.messages import HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

os.environ["TAVILY_API_KEY"] = "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"
from langchain_ollama import ChatOllama
from langchain_community.tools.tavily_search import TavilySearchResults
# 1. 创建 LLM
model = ChatOllama(model="qwen2.5:1.5b", temperature=0)

# 2. 创建搜索工具
search = TavilySearchResults(max_results=2)
tools = [search]

# 3. 绑定工具到模型
model_with_tools = model.bind_tools(tools)

# 4. 构建 prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个科学助手."),
    MessagesPlaceholder(variable_name="messages"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# 5. 创建 agent
agent = create_tool_calling_agent(model_with_tools, tools, prompt)

# 6. 创建执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 7. 测试调用 如果没提示 请使用工具TavilySearchResults 调用不了，或者在prompt提示使用工具
response = agent_executor.invoke({
    "messages": [HumanMessage(content="中山的天气怎么样?请使用工具TavilySearchResults")]
})
print(response)



